package com.easyOrder.service.impl;

import com.aliyun.openservices.ons.api.Message;
import com.easyOrder.core.json.JsonExceptionWrapper;
import com.easyOrder.core.mongo.log.LogComponent;
import com.easyOrder.core.mq.Callback;
import com.easyOrder.core.mq.TopicTag;
import com.easyOrder.core.utils.Exceptions;
import com.easyOrder.dao.MessageQueueExceptionMapper;
import com.easyOrder.model.MessageQueueExceptionWithBLOBs;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Date;
import java.util.List;

public class CallbackController implements Callback {

	@Autowired
	private MessageQueueExceptionMapper messageQueueExceptionMapper;

	@Autowired
	private LogComponent logService;

	private List<Callback> callbackExecutes;

	private static final Logger logger = Logger.getLogger(CallbackController.class);

	@Override
	public void execute(Message message) {
		callbackExecutes.forEach(callback -> {
			if (callback.getTag().name().equals(message.getTag())) {
				try {
					callback.execute(message);
				} catch (Exception e) {
					error(e, message);
				}
			}
		});
	}

	private void error(Exception e, Message message) {
		logger.error(e, e);
		MessageQueueExceptionWithBLOBs exception = new MessageQueueExceptionWithBLOBs();
		exception.setCreateTime(new Date());
		exception.setException(Exceptions.getStackTraceAsString(e));
		exception.setMessageBody(new String(message.getBody()));
		exception.setMessageId(message.getMsgID());
		messageQueueExceptionMapper.insert(exception);
		String exceptionTrace = JsonExceptionWrapper.getStackTrace(e);
		JsonExceptionWrapper result = new JsonExceptionWrapper(e);
		logService.insertExcept(result, exceptionTrace);
		logService.sendMail(message, exceptionTrace);
	}

	/**
	 * @return the callbackExecutes
	 */
	public List<Callback> getCallbackExecutes() {
		return callbackExecutes;
	}

	/**
	 * @param callbackExecutes
	 *            the callbackExecutes to set
	 */
	public void setCallbackExecutes(List<Callback> callbackExecutes) {
		this.callbackExecutes = callbackExecutes;
	}

	@Override
	public TopicTag getTag() {
		return TopicTag.callbackController;
	}
}
